package com.dayaokeji.rhythmschoolstudent.client.mine.bulletin;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;


import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.event.BulletinEvent;
import com.dayaokeji.rhythmschoolstudent.utils.BulletinUtil;
import com.dayaokeji.rhythmschoolstudent.utils.DateUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.BulletinApi;
import com.dayaokeji.server_api.domain.Bulletin;
import com.dayaokeji.server_api.domain.MessageReceipt;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import retrofit2.Call;

public class BulletinDetailActivity extends BaseActivity {

    public static final String EXTRA_BULLETIN_ENTITY = "bulletin_entity";

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_bulletin_title)
    TextView tvBulletinTitle;
    @BindView(R.id.tv_bulletin_content)
    TextView tvBulletinContent;
    @BindView(R.id.tv_bulletin_time)
    TextView tvBulletinTime;
    private Bulletin bulletin;

    private static final BulletinApi bulletinApi = ApiUtils.getApi(BulletinApi.class);
    private Call<ServerResponse<Void>> receiptCall;
    private Call<ServerResponse<Void>> deleteCall;

    public static void startBulletinDetailActivity(Context context, Bulletin bulletin) {
        Intent intent = new Intent(context, BulletinDetailActivity.class);
        intent.putExtra(EXTRA_BULLETIN_ENTITY, bulletin);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bulletin_detail);
        setSupportActionBar(toolbar);
        bulletin = (Bulletin) getIntent().getSerializableExtra(EXTRA_BULLETIN_ENTITY);

        if (bulletin == null) {
            ToastUtils.warning(R.string.data_incorrect);
            return;
        }

        init();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.bulletin_detail,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_del_bulletin:
                delDialog();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void init() {
        setData();
    }

    private void setData() {
        getSupportActionBar().setTitle(bulletin.getTitle());
        tvBulletinTitle.setText(bulletin.getTitle());
        tvBulletinContent.setText(bulletin.getInform());
        tvBulletinTime.setText(DateUtils.format(bulletin.getTime(),DateUtils.FORMAT_DATETIME_SHORT2));
        if (bulletin.getRevert() == BulletinUtil.NEED_RECEIPT && bulletin.getStatus() == BulletinUtil.NO_RECEIPT) {
            messageReceipt(bulletin);
        }
    }

    private void delDialog() {
        AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle("提示").setMessage("您确认要删除当前通知吗？").setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                delBulletin();
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).create();
        alertDialog.show();
        alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.warring_red));
        alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.gray));
    }

    /**
     * 删除消息
     */
    private void delBulletin() {
        Map<String,Integer> map = new HashMap<>();
        map.put("id",bulletin.getId());
        deleteCall = bulletinApi.delete(map);
        deleteCall.enqueue(new ServerCallback<Void>() {
            @Override
            public void onResponse(boolean success, ServerResponse<Void> response) {
                if (success) {
                    ToastUtils.success("删除成功");
                    EventBus.getDefault().post(new BulletinEvent());
                    ActivityStackManager.finish();
                }
            }
        });
    }

    /**
     * 消息回执请求
     * @param bulletin
     */
    private void messageReceipt(final Bulletin bulletin) {
        receiptCall = bulletinApi.receipt(new MessageReceipt(bulletin.getId(), BulletinUtil.ALREADY_RECEIPT));
        receiptCall.enqueue(new ServerCallback<Void>() {
            @Override
            public void onResponse(boolean success, ServerResponse<Void> response) {
                if (success) {
                    EventBus.getDefault().post(new BulletinEvent(bulletin));
                    bulletin.setStatus(BulletinUtil.ALREADY_RECEIPT);
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        if (receiptCall != null) {
            receiptCall.cancel();
        }
        if (deleteCall != null) {
            deleteCall.cancel();
        }
        super.onDestroy();
    }
}
